<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="../css/reset.css">
    <style>
        .shadow {
            width: 200px;
            height: 200px;
            background-color: rgba(0, 0, 0, 0.5);
            position: absolute;
            left: 50px;
            top: 50px;

        }
    </style>
</head>

<body>
    <div class="shadow"></div>
</body>
<script>
    // 需求: 鼠标拖拽盒子移动?
    // 1. 先按下 => 选中需要拖拽的盒子
    // 2. 在移动 => 盒子跟随鼠标在文档中移动
    // 3. 最后松开 => 盒子不在各随鼠标移动

    var shadow = document.getElementsByClassName("shadow")[0];

    var isPress = false;
    var posX = 0;
    var posY = 0;


    // 1. 先按下 => 选中需要拖拽的盒子 => 记录被按下的位置
    shadow.onmousedown = function (e) {
        var e = e || window.event;

        // 如果shadow 没有子内容
        posX = e.offsetX;
        posY = e.offsetY;
        console.log(posX, posY);

        // 如果shadow中有子内容 => 自己算
        // var posX = e.pageX - shadow.offsetLeft;
        // var posY = e.pageY - shadow.offsetTop;
        // console.log(posX, posY);

        isPress = true;
    }

    // 在移动 => 盒子跟随鼠标相对于按下的位置移动
    document.onmousemove = function (e) {
        if (!isPress) return false;

        var e = e || window.event;

        var x = e.pageX - posX;
        var y = e.pageY - posY;

        shadow.style.left = x + "px";
        shadow.style.top = y + "px";
    }

    document.onmouseup = function () {
        isPress = false;
    }






</script>

</html>